package com.lxm.enigma.wrappers;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: Lys
 * @Date 2022/5/25
 * @Describe
 **/
@Slf4j
public class EnigmaResponseWrapper extends HttpServletResponseWrapper {

    private ServletOutputStream filterOutput;

    private ByteArrayOutputStream output;

    private Class<?> returnType;


    public EnigmaResponseWrapper(HttpServletResponse response) {
        super(response);
        this.output = new ByteArrayOutputStream();
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (Objects.isNull(filterOutput)) {
            filterOutput = new ServletOutputStream() {
                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setWriteListener(WriteListener writeListener) {

                }

                @Override
                public void write(int b) throws IOException {
                    output.write(b);
                }
            };
        }
        return filterOutput;
    }

    public String getResponseData() {
        return output.toString();
    }
}
